<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class FollowPlanTemplateLib extends Model
{
    protected $table ="c_follow_plan_template_libs";

    public function tempmessage()
    {
        return $this->hasMany('App\Models\FollowPlanTemplateLibMessage',"template_lib_id");
    }
    public function clinic()
    {
        return $this->hasOne('App\Models\ClinicCategory','id',"clinic_id");
    }

    public function followTitle()
    {
        return $this->hasOne('App\Models\FollowTitle','id',"title_id");
    }

    public function doctor()
    {
        return $this->hasOne('App\Models\Doctor', 'id', "doctor_id");
    }


    public function add($filter)
    {
        $this->title = $filter['title'];
        $this->content = $filter['content'];
        $this->clinic_id = $filter['clinic_id'];
        $this->doctor_id = $filter['doctor_id'];
        $res = $this->save();
        if ($res) {
            $filter['temp_id'] = $this->id;
            $this->addPlanMessage($filter);
            return ["temp_id"=>$this->id];
        }
    }


    /**
     *  添加自动随访消息到模板
     */
    public function addPlanMessage($param)
    {
        $plan =  new FollowPlanTemplateLibMessage();
        $plan->message = $param['message'];
        $plan->date = $param['date'];
        $plan->template_lib_id = $param['temp_id'];
        return $plan->save();
    }


    public function detail($id)
    {
        return $this->where([['id','=',$id]])->with(['tempmessage','clinic','doctor'])->first()->toArray();
    }


    /**
     * 模板列表
     */
    public function getList($filter)
    {
        $where = [];
        if(isset($filter['clinic_id'])){
            $where[] = ['clinic_id','=',$filter['clinic_id']];
        }
        $res = $this::where($where)->with(['tempmessage','clinic','doctor'])->orderBy("id","desc")->simplePaginate()->toArray();
        $profession = new Professional();
        foreach($res['data'] as $k=>&$v){
            if(!empty($v['doctor'])){
                $v['doctor']['professional_name'] =$profession->where([['id','=',$v['doctor']['professional_id']]])->value("name");
            }
        }
        return $res;
    }
}
